package pr.lanmu.config.util;

import com.github.pagehelper.PageInfo;
import com.mybatisflex.core.paginate.Page;
import pr.lanmu.config.web.CustomPageInfo;

import java.util.List;

/**
 * 分页信息处理工具类，可处理pagehelper和mybatis-flex的分页结果统一
 */
public class PageUtil {
    public static <T> CustomPageInfo<T> getPageInfo(PageInfo<T> pageInfo) {
        return CustomPageInfo.<T>builder()
                .page(CustomPageInfo.PageInfo.builder()
                        .index(pageInfo.getPageNum())
                        .size(pageInfo.getPageSize())
                        .total(pageInfo.getTotal())
                        .build())
                .list(pageInfo.getList())
                .build();
    }


    public static <T> CustomPageInfo<T> getPageInfo(PageInfo<?> pageInfo, List<T> list) {
        return CustomPageInfo.<T>builder()
                .page(CustomPageInfo.PageInfo.builder()
                        .index(pageInfo.getPageNum())
                        .size(pageInfo.getPageSize())
                        .total(pageInfo.getTotal())
                        .build())
                .list(list)
                .build();
    }

    public static <T> CustomPageInfo<T> getPageInfo(Page<T> pageInfo) {
        return CustomPageInfo.<T>builder()
                .page(CustomPageInfo.PageInfo.builder()
                        .index(Math.toIntExact(pageInfo.getPageNumber()))
                        .size(Math.toIntExact(pageInfo.getPageSize()))
                        .total(pageInfo.getTotalRow())
                        .build())
                .list(pageInfo.getRecords())
                .build();
    }

    public static <T> CustomPageInfo<T> getPageInfo(Page<?> pageInfo, List<T> list) {
        return CustomPageInfo.<T>builder()
                .page(CustomPageInfo.PageInfo.builder()
                        .index(Math.toIntExact(pageInfo.getPageNumber()))
                        .size(Math.toIntExact(pageInfo.getPageSize()))
                        .total(pageInfo.getTotalRow())
                        .build())
                .list(list)
                .build();
    }

    public static <T, E> CustomPageInfo<E> getPageInfo(Page<T> pageInfo, Class<E> e) {
        return getPageInfo(pageInfo, ConvertUtil.listToType(pageInfo.getRecords(), e));
    }
}